from Database import *
import sqlparse
import sqlite3


def getDataBySql(sql: str) -> []:
    db = Database(
        host="81.68.216.231",
        user="root",
        password="Wb@980324",
        database="data"
    )
    # 查询数据
    try:
        results = db.execute_query(sql)
        data_objects = [DataModel(**row) for row in results]
        return data_objects;
    except Exception as e:
        raise Exception("sql执行出现异常")
    finally:
        db.disconnect()

from datetime import datetime

def default(o):
    if isinstance(o, datetime):
        return o.isoformat()
    raise TypeError("Unserializable object {}".format(o))


if __name__ == "__main__":
    result_list = getDataBySql("select * from sina_data limit 10")
    data = []
    if len(result_list) != 0:
        for data_model in result_list:
            dict_single_value = data_model.__dict__
            data.append(dict_single_value)

    json_result = json.dumps(data, ensure_ascii=False,default=default)

    print(json_result)
